package com.itheima.admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itheima.admin.DTO.LogDTO;
import com.itheima.admin.ENUM.logEnum;
import com.itheima.admin.mapper.LogMapper;
import com.itheima.admin.service.LogService;
import com.itheima.admin.vo.logVO;
import com.itheima.common.util.AppJwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lqj
 * @Date: 2022/08/27/15:42
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class LogServiceimpl implements LogService {

    private final LogMapper logMapper;


    /**
     * 登陆
     *
     * @param logvo logvo
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    @Override
    public Map<String, Object> Log(logVO logvo) {
        Map<String, Object> map = new ConcurrentHashMap<>(16);
        SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss");
        LogDTO logDTO = logMapper.selectUserInfo(logvo.getUserId());
        if (StringUtils.isEmpty(logvo.getUserId()) || StringUtils.isEmpty(logvo.getPassword())) {
            map.put("userInfo", logEnum.NAME_PASSWORD_NULL.getDescription());
            return map;
        }
        //账号不存在
        if (ObjectUtils.isEmpty(logDTO)) {
            map.put("userInfo", logEnum.USER_NULL.getDescription());
            return map;
        }
        String s = DigestUtils.md5DigestAsHex(logvo.getPassword().getBytes());
        //密码不正确
        if (StringUtils.isEmpty(logDTO.getPassword()) || !logDTO.getPassword().equals(s)) {
            map.put("userInfo", logEnum.PASSWORD_ERROR.getDescription());
            return map;
        }
        //登陆成功返回token
        String token = AppJwtUtil.createToken(logDTO.getId());
        map.put("token", token);
        map.put("Info",logEnum.LOGIN_SUCCEEDED.getDescription());
        map.put("上次登陆时间",dateFormat.format(logDTO.getLoginTime()));
        //修改上一次登陆时间
        logMapper.updateLoTime(logvo.getUserId());
        return map;
    }

    /**
     * 注册账号
     *
     * @param logdto logdto
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    @Override
    public Map<String, Object> register(LogDTO logdto) {
        Map<String, Object> map = new HashMap<>(16);
        if (StringUtils.isEmpty(logdto.getName()) || StringUtils.isEmpty(logdto.getPassword()) || StringUtils.isEmpty(logdto.getNickname()) || StringUtils.isEmpty(logdto.getPhone())) {
            map.put("erro:", logEnum.REQUIRED_NULL.getDescription());
            return map;
        }
        logdto.setPassword(DigestUtils.md5DigestAsHex(logdto.getPassword().getBytes()));
        int ii = (int) (Math.random() * 20000 + 10000);
        //生成唯一用户ID
        LogDTO logDTO = logMapper.selectUserInfo(String.valueOf(ii));
        StringBuffer userid = new StringBuffer();
        if (ObjectUtils.isEmpty(logDTO)){
            userid.append(ii);
        }
        while (ObjectUtils.isNotEmpty(logDTO)) {
            int iii = (int) (Math.random() * 20000 + 10000);
            LogDTO logDTO1 = logMapper.selectUserInfo(String.valueOf(iii));
            if (ObjectUtils.isEmpty(logDTO1)) {
                userid.append(iii);
                break;
            }
        }
        logdto.setUserId(userid.toString());
        logMapper.insertUser(logdto);
        map.put("erro:", logEnum.LOGIN_WAS_SUCCESSFUL.getDescription());
        map.put("账号",logdto.getUserId());
        return map;
    }


    /**
     * 下载报告
     *
     * @param response 响应
     * @throws Exception 异常
     */
    @Override
    public void extend(HttpServletResponse response) throws Exception {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(formatter);
        String fileName = URLEncoder.encode("行业利差分析" + format);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        ClassPathResource classPathResource = new ClassPathResource("templates/Test.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build();
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build();
        logVO logVO = new logVO();
        //Map<String, List<?>> log = Log(logVO);
        WriteSheet writeSheet = EasyExcel.writerSheet(0, "用户").build();
        WriteSheet writeSheet1 = EasyExcel.writerSheet(1, "用户二").build();
        WriteSheet writeSheet2 = EasyExcel.writerSheet(2, "用户二").build();
        //List<?> userInfo =  log.get("userInfo");
        excelWriter.fill(new FillWrapper("item", null), fillConfig, writeSheet);
        excelWriter.fill(new FillWrapper("item", null), fillConfig, writeSheet1);
        excelWriter.fill(new FillWrapper("item", null), fillConfig, writeSheet2);
        excelWriter.finish();
    }
}
